
import diyfroms from "components/diyform";
import yzAddressList from "components/ui_components/yz_addressList/index";
import yzService from "../../components/ui_components/yz_service.vue";
import equity from "./component/equity.vue";
import { Toast } from "vant";

export default {
  components: { yzService, equity, yzAddressList, diyfroms },
  data() {
    return {
      arr: [],
      num: 1,
      order_deductions: [],
      activity_count: 0,
      city: "",
      total_price: 0,
      form_id: "",
      applyStatus: "",
      payStatus: "",
      activity: {},
      activityId: "",
      activity_info: [],
      info: {},


      domain: document.domain,
      form: {
        name: "",
        domain: "",
        mobile: ""
      },
      authcode: "",
      count: "",
      timer: null,
      isNew: 0,
      show_domain: true,
      diyforms_show: false,
      isBinding: false,
      domain_show: false,

      loading: false,
      btn_flag: true,
      is_show_address: true,
      showKefu: false,
      cservice: "",
      service_mobile: "",
      service_QRcode: "",

      _currentAddress: {},

      status: 1,
      show_address: false,
      mobile: "",
      realname: "",
      address: "",
      showAddress: false,
      selected: 0,
      yzAddressListOptions: {}, //地址组件配置信息（可选）

      right: {},
      code: "",
      encrypted_code: "",
      verify_token: "",

      rotation: [],
      introduce: "",
      has_domain: "",
      plugin_id: "",
      store_id:"",
    };
  },
  activated() {
    this.info = "";
    this.code = "";
    this.loading = false;
    this.status = 1;
    this.btn_flag = true;
    this.showKefu = false;
    if(this.$route.params.tiktok_shop_id){
      this.id=this.$route.params.tiktok_shop_id;
    }else{
      this.id = this.$route.query.id;
    }
    if(this.$route.params.store_id){
      this.store_id=this.$route.params.store_id;
    }
    this.getData();
    this.getKefu();
  },
  methods: {
    close_popup() {
      this.diyforms_show = false;
      this.info = "";
      this.check(1);
    },
    checkDomain() {
      if (this.form.domain.indexOf('https://') > -1 || this.form.domain.indexOf('http://') > -1) {
        return false;
      }
      return true;
    },
    changeNew() {
      this.isNew = !this.isNew;
    },
    toSave() {
      if (this.isNew && !this.form.name) {
        Toast("请填写公司/个人名称");
        return;
      }

      if (!this.form.domain) {
        Toast("请填写域名");
        return;
      }

      if (!this.checkDomain()) {
        this.$dialog.alert({ message: '域名格式不正确: 请填写没有https://或http:// 格式的域名' });
        return;
      }

      if (!this.form.mobile) {
        Toast("请填写手机号");
        return;
      }

      if (!this.authcode) {
        Toast("请先填写验证码");
        return;
      }

      let url = "";
      let json = {};
      if (this.isNew) {
        url = "plugin.product-market.api.client.index.add";
        if (this.plugin_id === 58) {
          url = "plugin.market-sub.api.client.index.add";
        }
        json = {
          domain: this.form.domain,
          mobile: this.form.mobile,
          code: this.authcode,
          name: this.form.name
        };
      } else {
        url = "plugin.product-market.api.client.index.bind";
        if (this.plugin_id === 58) {
          url = "plugin.market-sub.api.client.index.bind";
        }
        json = {
          domain: this.form.domain,
          mobile: this.form.mobile,
          code: this.authcode,
        };
      }
      $http
        .post(url, json, "...").then(response => {
          if (response.result === 1) {
            this.$dialog.alert({ message: response.msg });
            this.check(1);
          } else {
            this.$dialog.alert({ message: response.msg });

          }
        },
          response => {
            this.$dialog.alert({ message: response.msg });

          }
        );
    },
    sureIdentify() {
      if (!this.form.mobile) {
        Toast("请先填写手机号");
        return;
      }
      let url = "plugin.product-market.api.client.index.send-code";
      if (this.plugin_id === 58) {
        url = "plugin.market-sub.api.client.index.send-code";
      }
      let json = {
        mobile: this.form.mobile
      };
      const TIME_COUNT = 60;
      $http
        .post(url, json, "...").then(response => {
          if (response.result === 1) {
            Toast("已发送");
            if (!this.timer) {
              this.count = TIME_COUNT;
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--;
                } else {
                  clearInterval(this.timer);
                  this.timer = null;
                }
              }, 1000);
            }
          } else {
            this.$dialog.alert({ message: response.msg });

          }
        },
          response => {
            this.$dialog.alert({ message: response.msg });

          }
        );
    },
    closed_domain() {
      this.show_domain = true;
    },
    diyformData() {
      let json = {
        activity_id: this.activityId
      };
      $http
        .post("plugin.activity-apply.api.Activity.getActivityEnrol", json)
        .then(response => {
          if (response.data && response.data.enrol == 2) {
            //添加权限
            return Toast(response.msg);
          }
          if (response.result === 1) {
            Toast(response.msg);
            this.payStatus = response.data.enrol;
            this.applyStatus = response.data.status;
            this.getActivity(json);
          } else {
            this.payStatus = response.data.enrol;
            this.getActivity(json);
          }
        })
        .catch(err => {
          console.log(err);
        });

    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes()) + ":";
      let s = this.change(date.getSeconds());
      return Y + M + D + h + m + s;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    getActivity(json) {
      $http
        .get("plugin.activity-apply.api.Activity.getActivity", json, "加载中")
        .then(({ result, data, msg }) => {
          if (result === 1) {
            this.form_id = String(data.form_id);
            this.activity = data;
            this.activity_count =
              data.has_many_pay_order.length > 0
                ? data.has_many_pay_order[0].count
                : 0;
            this.city = data.city_name || '';
            this.total_price = data.cash;
            if (data.cash > 0) {
              this.priceChange();
            } else {
              this.info = {
                dispatch_type_id: 0,
                activity_id: data.id,
                test_uid: window.localStorage.uid,
                lecturer_id: data.lecturer_id,
                calssify_id: data.calssify_id,
                goods: JSON.stringify([
                  {
                    goods_id: data.goods_id,
                    total: this.num,
                    option_id: 0
                  }
                ]),
                form_id: ""
              };
            }

          } else {
            Toast(msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    checkData() {
      let url = "plugin.product-market.api.client.index";
      if (this.plugin_id === 58) {
        url = "plugin.market-sub.api.client.index";
      }
      $http
        .get(
          url,
          {},
          "获取中"
        )
        .then(response => {
          if (response.result === 1) {
            this.isBinding = false;
          } else {
            // 已经绑定过的不操作
            this.isBinding = true;
            this.$dialog.alert({ message: response.msg })
              .then(() => {
                this.show_domain = true;
                // this.$router.go(-1);
              }).catch(() => { });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    toChange(str) {
      this.show_domain = false;
      if (str === 'new') {
        this.isNew = 1;
        // this.toRouter('changeSite', 'replace', {}, {
        //   isNew: 1,
        //   plugin_id: this.plugin_id
        // });
      } else {
        this.isNew = 2;
        // this.toRouter('changeSite', 'replace', {}, { plugin_id: this.plugin_id });
      }
    },
    toRouter(url, jumpType, params, query) {
      if (jumpType === 'replace') {
        this.$router.replace(
          this.fun.getUrl(url, {
            tag: this.$route.query.tag,
            goodsId: this.$route.query.goodsId,
            optionsId: this.$route.query.optionsId,
            total: this.$route.query.total,
            id: this.diyform_id,
            form_data_id: this.form_data_id,
            cart_ids: this.$route.query.cart_ids,
            store_id: this.$route.query.store_id,
            ...params
          }, { ...query })
        );
      }
    },
    getData() {
      $http.post("plugin.tiktok-verify-ticket.api.verify.index", { id: this.id }, "").then(({ result, msg, data }) => {
        if (result !== 1) {
          return this.$toast(msg);
        }
        this.rotation = data.rotation;
        this.introduce = data.introduce;
      })
    },
    getKefu() {
      $http.get("plugin.tiktok-verify-ticket.api.verify.customer-service").then(({ result, msg, data }) => {
        if (result !== 1) {
          return this.$toast(msg);
        }
        this.service_mobile = data.service_mobile;
        this.service_QRcode = data.service_QRcode
        this.cservice = data.cservice;
      })
    },
    getAddress() {
      $http.get("member.member-address.index", {}, "获取中").then(response => {
        if (response.result === 1) {
          let _address = response.data.filter(function (item) {
            return item.isdefault === 1;
          });
          this._currentAddress = _address[0];
          this.show_address = false;
          this.realname = _address[0].username;
          this.mobile = _address[0].mobile;
          this.address = `${_address[0].province} ${_address[0].city} ${_address[0].district} ${_address[0].street || ''} ${_address[0].address}`
        } else {
          Toast(response.msg);
        }
      },
        function (response) {
          console.log(response);
        }
      );
    },
    // 设置地址界面
    setAddressViewData(model) {
      if (model == undefined || model == "" || model == []) {
        return;
      }
      this._currentAddress = model;


      this.realname = this.fun.isTextEmpty(model.username)
        ? ""
        : model.username;
      this.mobile = this.fun.isTextEmpty(model.mobile) ? "" : model.mobile;
      this.address = this.fun.isTextEmpty(model.province)
        ? ""
        : model.province +
        " " +
        model.city +
        " " +
        model.district +
        " " +
        (this.fun.isTextEmpty(model.street) ? "" : model.street + " ") +
        model.address;
    },

    confirmSelectAddress(item) {
      this.setAddressViewData(item);
      this.showAddress = false;
    },
    //显示地址pop
    showAddressFun() {
      if (this.status == 3) {
        return;
      }
      // 获取收货地址
      this.yzAddressListOptions = {
        is_open_store_delivery: this.is_open_store_delivery,
        selected: this.selected
      };
      this.showAddress = true;
    },
    check(status) {
      console.log("走这里========");
      if (this.loading) {
        return;
      }
      let url = '', json = {};
      if (status == 1) {
        url = 'plugin.tiktok-verify-ticket.api.verify.prepare';
        json = {
          code: this.code,
          id: this.id
        }
        this.loading = true;
        $http.post(url, json).then(({ result, msg, data }) => {
          if (result !== 1) {
            this.loading = false;
            return this.$toast(msg);
          }
          this.encrypted_code = data.encrypted_code;
          this.verify_token = data.verify_token;
          this.status = 2;
          this.has_domain = data.has_domain;
          this.activity_info = data.activity_info || [];
          this.right = data.right;
          if (data.need_address) {
            this.is_show_address = true;
            if (data.default_address) {
              this.realname = data.default_address.username;
              this.mobile = data.default_address.mobile;
              this.address = `${data.default_address.province} ${data.default_address.city} ${data.default_address.district} ${data.default_address.address}`;
              this._currentAddress = data.default_address;
            } else {
              this.getAddress();
            }
          } else {
            this.is_show_address = false;
          }
          this.loading = false;
        })
      } else if (status == 2) {
        url = 'plugin.tiktok-verify-ticket.api.verify.startVerify';
        json = {
          encrypted_code: this.encrypted_code,
          verify_token: this.verify_token,
          code: this.code,
          id:this.id,
        }
        if(this.store_id){
          json.shop_id=this.store_id;
        }
        if (this.is_show_address) {
          if (JSON.stringify(this._currentAddress) == "{}") {
            return this.$toast("请选择地址")
          }
          json.address = encodeURIComponent(JSON.stringify(this._currentAddress))
        }
        console.log(this.chek_goods_type(), "this.chek_goods_type()==")

        if (this.chek_goods_type()) {//检查商品内是否有应用市场商品、应用市场子平台商品、活动报名
          this.loading = true;
          $http.post(url, json).then(({ result, msg, data }) => {
            if (result !== 1) {
              this.loading = false;
              return this.$toast(msg);
            }
            this.$toast(msg);
            this.$refs['equityRoot'].getOrder(data.id);
            this.status = 3;
            this.loading = false;
          })
        }
      }

    },
    chek_goods_type() {
      let result = this.activity_info.filter(item => {
        if (!item.has_sign) {
          return item;
        }
      })
      if (result && result.length !== 0) {
        this.activityId = result[0].id;
        this.diyforms_show = true;
        return false
      } else {
        for (let j = 0; j < this.right.good.length; j++) {
          if (this.right.good[j].plugin_id === 58) {
            this.plugin_id = 58;
          }
        }
        //为空时代表有应用市场或应用市场子平台上单，并且没有绑定站点
        if (this.has_domain !== null && this.has_domain == '') {
          this.domain_show = true;
          return false
        }
      }
      return true;
    },
    goto() {
      this.$router.push(this.fun.getUrl("tiktok_writeoff_record"))
    },
    priceChange() {
      let that = this;
      let json = {
        address: JSON.stringify({}),
        dispatch_type_id: 0,
        goods_id: this.activity.goods_id,
        total: this.num,
        option_id: "",
        orders: JSON.stringify(this.arr),
        member_coupon_ids: ""
      };
      $http.get("order.goods-buy", json, "").then(
        function (response) {
          if (response.result == 1) {
            that.total_price = response.data.total_price;
            that.pre_id = response.data.orders[0].pre_id;
            that.order_deductions = response.data.orders[0].order_deductions;
            if (response.data.discount && response.data.discount.default_deduction && response.data.discount.default_deduction != 0) {
              // 获取第一次接口默认积分抵扣
              that.default_deduction = response.data.discount.default_deduction;
            }
            for (let val in that.order_deductions) {
              if (
                that.order_deductions[val].code == "point" &&
                that.order_deductions[val].checked == true
              ) {
                //that.nochecked = true;
                that.arr.push("point");
                that.info = {
                  orders: JSON.stringify([
                    {
                      deduction_ids: that.arr,
                      pre_id: that.pre_id
                    }
                  ]),
                  dispatch_type_id: 0,
                  activity_id: that.activity.id,
                  test_uid: window.localStorage.uid,
                  lecturer_id: that.activity.lecturer_id,
                  calssify_id: that.activity.calssify_id,
                  goods: JSON.stringify([
                    {
                      goods_id: that.activity.goods_id,
                      total: that.num,
                      option_id: 0
                    }
                  ]),
                  form_id: ""
                };
              } else {
                that.info = {
                  orders: JSON.stringify([
                    {
                      deduction_ids: that.arr,
                      pre_id: that.pre_id
                    }
                  ]),
                  dispatch_type_id: 0,
                  activity_id: that.activityId,
                  test_uid: window.localStorage.uid,
                  lecturer_id: that.activity.lecturer_id,
                  calssify_id: that.activity.calssify_id,
                  goods: JSON.stringify([
                    {
                      goods_id: that.activity.goods_id,
                      total: that.num,
                      option_id: 0
                    }
                  ]),
                  form_id: ""
                };
              }
            }
          } else {
            // that.$router.go(-1);
            Toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
  }
};